// 内容与原文件一致，迁移到 admin 目录
<template>
  <div class="major-view">
    <!-- 页面标题栏 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <i class="el-icon-collection"></i>
          专业管理
        </h1>
        <p class="page-description">管理学校的专业信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">
          新增专业
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-search"></i> 搜索筛选</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="专业名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入专业名称" 
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleSearch">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="所属系">
          <el-input 
            v-model="searchForm.departmentName" 
            placeholder="请输入系名" 
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleSearch">
            <i slot="prefix" class="el-input__icon el-icon-office-building"></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-menu"></i> 专业列表</span>
        <span class="table-count">共 {{ total }} 条记录</span>
      </div>
      
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        stripe
        border
        empty-text="暂无数据">
        <el-table-column prop="id" label="专业ID" width="100" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="info">{{ scope.row.id }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="专业名称" min-width="200">
          <template slot-scope="scope">
            <div class="name-cell">
              <i class="el-icon-collection name-icon"></i>
              <span class="name-text">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="所属系" min-width="150">
          <template slot-scope="scope">
            <el-tag size="small" type="success">
              {{ scope.row.departmentName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button 
                size="mini" 
                type="primary" 
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
                class="action-btn edit-btn">
                编辑
              </el-button>
              <el-button 
                size="mini" 
                type="danger" 
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                class="action-btn delete-btn">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background>
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="form" 
        label-width="100px"
        label-position="right">
        <el-form-item label="专业名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入专业名称"
            maxlength="50"
            show-word-limit
            clearable>
            <i slot="prefix" class="el-input__icon el-icon-collection"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="所属系" prop="departmentId">
          <el-select 
            v-model="form.departmentId" 
            placeholder="请选择所属系"
            style="width: 100%"
            clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">ID: {{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" icon="el-icon-close">
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
          icon="el-icon-check">
          {{ submitLoading ? '提交中...' : '确定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMajorPage, getMajorPageCount, saveMajor, deleteMajor, getMajorById, getDepartmentNames } from '@/api'

export default {
  name: 'MajorView',
  data() {
    return {
      searchForm: {
        name: '',
        departmentName: ''
      },
      tableData: [],
      departmentOptions: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增专业',
      submitLoading: false,
      form: {
        id: -1,
        name: '',
        departmentId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入专业名称', trigger: 'blur' },
          { min: 2, max: 50, message: '专业名称长度在 2 到 50 个字符', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/, message: '专业名称只能包含中文、英文、数字和空格', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请选择所属系', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadDepartments()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const countRes = await getMajorPageCount(this.searchForm)
        if (countRes.code === 0) {
          this.total = countRes.data * this.pageSize
        }
        const res = await getMajorPage(this.currentPage, this.searchForm)
        if (res.code === 0) {
          this.tableData = res.data || []
        }
      } catch (error) {
        this.$message.error('加载数据失败')
        console.error('加载专业列表数据失败:', error)
      } finally {
        this.loading = false
      }
    },
    async loadDepartments() {
      try {
        const res = await getDepartmentNames()
        if (res.code === 0) {
          this.departmentOptions = res.data || []
        }
      } catch (error) {
        console.error('加载系列表失败:', error)
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    resetSearch() {
      this.searchForm = { name: '', departmentName: '' }
      this.handleSearch()
    },
    showAddDialog() {
      this.dialogTitle = '新增专业'
      this.form = { id: -1, name: '', departmentId: '' }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    async handleEdit(row) {
      try {
        this.loading = true
        const res = await getMajorById(row.id)
        if (res.code === 0) {
          this.dialogTitle = '编辑专业'
          this.form = { ...res.data }
          this.dialogVisible = true
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        } else {
          this.$message.error(res.message || '获取专业信息失败')
        }
      } catch (error) {
        this.$message.error('获取专业信息失败')
        console.error('获取专业信息失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleDelete(row) {
      this.$confirm(`确定要删除专业"${row.name}"吗？`, '确认删除', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        try {
          const res = await deleteMajor(row.id)
          if (res.code === 0) {
            this.$message.success('删除成功')
            if (this.tableData.length === 1 && this.currentPage > 1) {
              this.currentPage--
            }
            this.loadData()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error('删除专业失败:', error)
        }
      }).catch(() => {})
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        this.submitLoading = true
        const res = await saveMajor(this.form)
        if (res.code === 0) {
          this.$message.success(this.form.id === -1 ? '新增成功' : '编辑成功')
          this.dialogVisible = false
          if (this.form.id === -1) {
            this.currentPage = 1
          }
          this.loadData()
        } else {
          this.$message.error(res.message || (this.form.id === -1 ? '新增失败' : '编辑失败'))
        }
      } catch (error) {
        if (error === false) return
        this.$message.error(this.form.id === -1 ? '新增失败' : '编辑失败')
        console.error('保存专业信息失败:', error)
      } finally {
        this.submitLoading = false
      }
    },
    handleDialogClose() {
      this.$refs.form && this.$refs.form.resetFields()
      this.submitLoading = false
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.major-view { padding: 24px; min-height: calc(100vh - 120px); background: #f5f6fa; }
.page-header { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:24px; background:white; padding:24px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.1); border:1px solid #e8e9ea; }
.header-left { flex:1; }
.page-title { margin:0 0 8px 0; font-size:28px; font-weight:700; color:#1a1a1a; display:flex; align-items:center; }
.page-title i { margin-right:12px; color:#409eff; font-size:32px; }
.page-description { margin:0; color:#6c757d; font-size:15px; font-weight:400; }
.header-right { display:flex; align-items:center; }
.card-header { display:flex; justify-content:space-between; align-items:center; font-weight:600; color:#262626; font-size:16px; }
.table-count { font-size:14px; color:#909399; }
.search-card { margin-bottom:16px; }
.pagination-container { margin-top:16px; text-align:right; }
.action-buttons { display:flex; gap:8px; justify-content:center; align-items:center; }
:deep(.action-btn) { width:60px !important; height:28px !important; padding:0 !important; border-radius:4px !important; font-size:12px !important; display:flex !important; align-items:center !important; justify-content:center !important; min-width:60px !important; }
:deep(.edit-btn) { background-color:#409eff !important; border-color:#409eff !important; color:white !important; }
:deep(.edit-btn:hover) { background-color:#66b1ff !important; border-color:#66b1ff !important; }
:deep(.delete-btn) { background-color:#f56c6c !important; border-color:#f56c6c !important; color:white !important; }
:deep(.delete-btn:hover) { background-color:#f78989 !important; border-color:#f78989 !important; }
</style>
